package cn.mothin.service.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.mothin.bean.easyui.DataContent;
import cn.mothin.dao.FunctionItemDao;
import cn.mothin.dao.FunctionModuleDao;
import cn.mothin.dao.MenuConfigDao;
import cn.mothin.dao.MenuItemConfigDao;
import cn.mothin.dao.RoleModulePermissionDao;
import cn.mothin.dao.SystemRoleDao;
import cn.mothin.entity.FunctionItem;
import cn.mothin.entity.FunctionModule;
import cn.mothin.entity.MenuConfig;
import cn.mothin.entity.MenuItemConfig;
import cn.mothin.entity.SystemRole;
import cn.mothin.frame.bean.ActionResult;
import cn.mothin.frame.core.base.BaseService;
import cn.mothin.frame.help.UniqueCode;
import cn.mothin.frame.util.StringUtil;
import cn.mothin.vo.system.PermissionTreeData;
import cn.mothin.vo.system.RoleForm;

import com.google.gson.Gson;

@Service("54031a707b0bf81ac00a981c")
public class RoleService extends BaseService {
    @Autowired
    private SystemRoleDao systemRoleDao;
    @Autowired
    private MenuConfigDao menuConfigDao;
    @Autowired
    private MenuItemConfigDao menuItemConfigDao;
    @Autowired
    private FunctionItemDao functionItemDao;
    @Autowired
    private FunctionModuleDao functionModuleDao;
    @Autowired
    private RoleModulePermissionDao roleModulePermissionDao;

    public String query(RoleForm roleForm) {
        String sql = "SELECT * FROM system_role WHERE deleted<>TRUE ";
        return sqlHelper.queryJson(roleForm, sql);
    }

    /**
     * 查询全部的角色(控件使用)
     * 
     * @return Json数据
     */
    public String queryRoleJson(RoleForm roleForm) {
        List<DataContent> list = new ArrayList<DataContent>();
        List<SystemRole> roleList = systemRoleDao.queryAll();
        if (roleList.size() > 0) {
            for (int i = 0; i < roleList.size(); i++) {
                SystemRole systemRole = roleList.get(i);
                DataContent roleData = new DataContent();
                roleData.setId(systemRole.getId());
                roleData.setText(systemRole.getRoleName());
                roleData.setSelected(false);
                list.add(roleData);
            }
        }
        if (!StringUtil.isNullOrEmpty(roleForm.getSystemUserId())) {
            List<String> roles = systemRoleDao.querySystemUserRoles(roleForm
                    .getSystemUserId());
            if (list.size() > 0) {
                for (DataContent roleData : list) {
                    if (roles.contains(roleData.getId())) {
                        roleData.setSelected(true);
                    }
                }
            }
        }
        return toJson(list);
    }

    /**
     * 根据id查询角色
     * 
     * @param systemRoleForm
     * @return 0： 成功；1：不存在；2：已删除
     */
    public int queryRoleById(RoleForm roleForm) {
        SystemRole systemRole = systemRoleDao.get(roleForm.getSystemRole()
                .getId());
        if (systemRole == null) {
            return 1;
        } else if (systemRole.isDeleted()) {
            return 2;
        }
        roleForm.getSystemRole().setRoleName(systemRole.getRoleName());
        roleForm.getSystemRole().setMemo(systemRole.getMemo());
        return 0;
    }

    /**
     * 添加新角色
     * 
     * @param systemRoleForm
     * @param loginUser
     * @return 0：成功，1：角色名称已存在
     */
    public ActionResult addSystemRole(RoleForm roleForm) {
        ActionResult result = ActionResult.getInstance();

        if (systemRoleDao.checkExistedByName(roleForm.getSystemRole()
                .getRoleName())) {
            result.setOk(false);
            result.setMessage("相同名称的角色已存在");
        } else {
            String id = UniqueCode.make();
            SystemRole systemRole = new SystemRole();
            systemRole.setId(id);
            systemRole.setRoleName(roleForm.getSystemRole().getRoleName());
            systemRole.setMemo(roleForm.getSystemRole().getMemo());
            systemRoleDao.save(systemRole);

            result.setValue(id);
        }
        return result;
    }

    /**
     * 修改角色
     * 
     * @param systemRoleForm
     * @param loginUser
     * @return 0： 成功；1：不存在；2：已删除；3：名字已存在
     */
    public int update(RoleForm roleForm) {
        SystemRole systemRole = systemRoleDao.get(roleForm.getSystemRole()
                .getId());
        if (systemRole == null) {
            return 1;
        } else if (systemRole.isDeleted()) {
            return 2;
        } else {
            if (systemRoleDao.checkExistedByNameWithOutId(roleForm
                    .getSystemRole().getId(), roleForm.getSystemRole()
                    .getRoleName())) {
                return 3;
            }
        }
        systemRole.setRoleName(roleForm.getSystemRole().getRoleName());
        systemRole.setMemo(roleForm.getSystemRole().getMemo());
        systemRoleDao.update(systemRole);
        return 0;
    }

    /**
     * 删除角色
     * 
     * @param systemRoleForm
     * @param loginUser
     * @return 0： 成功；1：不存在；2：已删除；
     */
    public int delete(RoleForm roleForm) {
        SystemRole systemRole = systemRoleDao.get(roleForm.getSystemRole()
                .getId());
        if (systemRole == null) {
            return 1;
        } else if (systemRole.isDeleted()) {
            return 2;
        }
        systemRole.setDeleted(true);
        systemRoleDao.update(systemRole);
        return 0;
    }

    /**
     * 角色权限查看
     * 
     * @param systemRoleForm
     */
    public List<PermissionTreeData> queryPermission(RoleForm roleForm) {
        if (roleForm.getSystemRole() == null
                || StringUtil.isNullOrEmpty(roleForm.getSystemRole().getId())) {
            return null;
        }
        return queryMenu(null, roleForm.getSystemRole().getId());
    }

    // ***
    private List<PermissionTreeData> queryMenu(PermissionTreeData parent,
            String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();

        List<MenuConfig> menuConfigs = menuConfigDao
                .findMenuConfigs(parent == null ? null : parent.getId());
        for (int i = 0; i < menuConfigs.size(); i++) {
            MenuConfig menuConfig = menuConfigs.get(i);
            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(menuConfig.getIco());
            permissionTreeData.setId(menuConfig.getId());
            permissionTreeData.setName(menuConfig.getName());
            permissionTreeData.setMemo(menuConfig.getMemo());
            permissionTreeData.setOrdinal(menuConfig.getOrdinal());
            permissionTreeData.setNodeType(PermissionTreeData.MENU_PACKET);

            queryMenuItems(permissionTreeData, roleId);
            queryMenu(permissionTreeData, roleId);

            if (permissionTreeData.getChildren() != null
                    && permissionTreeData.getChildren().size() > 0) {
                permissionTreeDataList.add(permissionTreeData);
            }
        }

        if (parent != null) {
            parent.addChild(permissionTreeDataList);
        }
        return permissionTreeDataList;
    }

    // 2013-05-24
    private void queryMenuItems(PermissionTreeData parent, String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();
        List<MenuItemConfig> menuItemConfigList = menuItemConfigDao
                .findByMenuId(parent.getId(), roleId);
        for (int i = 0; i < menuItemConfigList.size(); i++) {
            MenuItemConfig menuItemConfig = menuItemConfigList.get(i);
            FunctionModule functionModule = functionModuleDao
                    .get(menuItemConfig.getFunctionModuleId());

            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(functionModule.getIco());
            permissionTreeData.setId(functionModule.getId());
            permissionTreeData.setModuleId(functionModule.getId());
            permissionTreeData.setName(functionModule.getName());
            permissionTreeData.setMemo(functionModule.getMemo());
            permissionTreeData.setOrdinal(menuItemConfig.getOrdinal());
            permissionTreeData.setNodeType(PermissionTreeData.MODULE);
            queryItem(permissionTreeData, roleId);
            queryModule(permissionTreeData, roleId);
            permissionTreeDataList.add(permissionTreeData);
        }
        parent.addChild(permissionTreeDataList);
    }

    private void queryModule(PermissionTreeData parent, String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();

        List<FunctionModule> functionModules = functionModuleDao
                .findSubFunctionModuleListByModuleId(parent.getId(), roleId);
        for (int i = 0; i < functionModules.size(); i++) {
            FunctionModule functionModule = functionModules.get(i);
            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(functionModule.getIco());
            permissionTreeData.setId(functionModule.getId());
            permissionTreeData.setModuleId(functionModule.getId());
            permissionTreeData.setName(functionModule.getName());
            permissionTreeData.setMemo(functionModule.getMemo());
            permissionTreeData.setOrdinal(i);
            permissionTreeData.setNodeType(PermissionTreeData.MODULE);
            queryModule(permissionTreeData, roleId);
            queryItem(permissionTreeData, roleId);
            permissionTreeDataList.add(permissionTreeData);
        }
        parent.addChild(permissionTreeDataList);
    }

    private void queryItem(PermissionTreeData parent, String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();

        List<FunctionItem> functionItems = null;
        if (parent.getNodeType() == PermissionTreeData.MODULE) {
            functionItems = functionItemDao.querySub(parent.getId(), null,
                    roleId);
        } else {
            functionItems = functionItemDao.querySub(parent.getModuleId(),
                    parent.getId(), roleId);
        }

        for (int i = 0; i < functionItems.size(); i++) {
            FunctionItem functionItem = functionItems.get(i);
            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(functionItem.getIco());
            permissionTreeData.setId(functionItem.getId());
            permissionTreeData.setModuleId(parent.getModuleId());
            permissionTreeData.setName(functionItem.getName());
            permissionTreeData.setMemo(functionItem.getMemo());
            permissionTreeData.setOrdinal(i);
            permissionTreeData.setNodeType(PermissionTreeData.ITEM);
            queryItem(permissionTreeData, roleId);
            permissionTreeDataList.add(permissionTreeData);
        }
        parent.addChild(permissionTreeDataList);
    }

    /**
     * 查询需进行配置的权限信息
     * 
     * @param systemRoleForm
     * @return
     */
    public List<PermissionTreeData> queryPermissionForUpdate(RoleForm roleForm) {
        if (roleForm.getSystemRole() == null) {
            return null;
        }
        String roleId = roleForm.getSystemRole().getId();
        if (StringUtil.isNullOrEmpty(roleId)) {
            return null;
        }
        List<PermissionTreeData> list = queryMenuForConfig(null, roleId);
        return list;
    }

    private List<PermissionTreeData> queryMenuForConfig(
            PermissionTreeData parent, String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();

        List<MenuConfig> menuConfigs = menuConfigDao
                .findMenuConfigs(parent == null ? null : parent.getId());
        for (int i = 0; i < menuConfigs.size(); i++) {
            MenuConfig menuConfig = menuConfigs.get(i);
            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(menuConfig.getIco());
            permissionTreeData.setId(menuConfig.getId());
            permissionTreeData.setName(menuConfig.getName());
            permissionTreeData.setMemo(menuConfig.getMemo());
            permissionTreeData.setOrdinal(menuConfig.getOrdinal());
            permissionTreeData.setNodeType(PermissionTreeData.MENU_PACKET);
            queryMenuItemsForConfig(permissionTreeData, roleId);
            permissionTreeDataList.add(permissionTreeData);
            queryMenuForConfig(permissionTreeData, roleId);
        }

        if (parent != null) {
            parent.addChild(permissionTreeDataList);
        }
        return permissionTreeDataList;
    }

    private void queryMenuItemsForConfig(PermissionTreeData parent,
            String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();
        List<MenuItemConfig> menuItemConfigList = menuItemConfigDao
                .findByMenuId(parent.getId());
        for (int i = 0; i < menuItemConfigList.size(); i++) {
            MenuItemConfig menuItemConfig = menuItemConfigList.get(i);
            FunctionModule functionModule = functionModuleDao
                    .get(menuItemConfig.getFunctionModuleId());

            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(functionModule.getIco());
            permissionTreeData.setId(functionModule.getId());
            permissionTreeData.setModuleId(functionModule.getId());
            permissionTreeData.setName(functionModule.getName());
            permissionTreeData.setMemo(functionModule.getMemo());
            permissionTreeData.setOrdinal(menuItemConfig.getOrdinal());
            permissionTreeData.setNodeType(PermissionTreeData.MODULE);
            if (roleModulePermissionDao.checkPermission(
                    permissionTreeData.getId(), roleId)) {
                permissionTreeData.setIntChecked(true);
                permissionTreeData.setChecked(true);
            }
            permissionTreeDataList.add(permissionTreeData);
            queryModuleForConfig(permissionTreeData, roleId);
            queryItemForConfig(permissionTreeData, roleId);
        }
        parent.addChild(permissionTreeDataList);
    }

    private void queryModuleForConfig(PermissionTreeData parent, String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();

        List<FunctionModule> functionModules = functionModuleDao
                .findSubFunctionModuleListByModuleId(parent.getId());

        for (int i = 0; i < functionModules.size(); i++) {
            FunctionModule functionModule = functionModules.get(i);
            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(functionModule.getIco());
            permissionTreeData.setId(functionModule.getId());
            permissionTreeData.setModuleId(functionModule.getId());
            permissionTreeData.setName(functionModule.getName());
            permissionTreeData.setMemo(functionModule.getMemo());
            permissionTreeData.setHostId(parent.getId());
            permissionTreeData.setOrdinal(i);
            permissionTreeData.setNodeType(PermissionTreeData.MODULE);
            if (roleModulePermissionDao.checkPermission(functionModule.getId(),
                    roleId)) {
                permissionTreeData.setIntChecked(true);
                permissionTreeData.setChecked(true);
            }
            queryModuleForConfig(permissionTreeData, roleId);
            queryItemForConfig(permissionTreeData, roleId);
            permissionTreeDataList.add(permissionTreeData);
        }
        parent.addChild(permissionTreeDataList);
    }

    private void queryItemForConfig(PermissionTreeData parent, String roleId) {
        List<PermissionTreeData> permissionTreeDataList = new ArrayList<PermissionTreeData>();

        List<FunctionItem> functionItems = null;
        if (parent.getNodeType() == PermissionTreeData.MODULE) {
            functionItems = functionItemDao.querySub(parent.getId(), null);
        } else {
            functionItems = functionItemDao.querySub(parent.getModuleId(),
                    parent.getId());
        }

        for (int i = 0; i < functionItems.size(); i++) {
            FunctionItem functionItem = functionItems.get(i);
            PermissionTreeData permissionTreeData = new PermissionTreeData();
            permissionTreeData.setIcon(functionItem.getIco());
            permissionTreeData.setId(functionItem.getId());
            permissionTreeData.setModuleId(parent.getModuleId());
            permissionTreeData.setName(functionItem.getName());
            permissionTreeData.setMemo(functionItem.getMemo());
            permissionTreeData.setOrdinal(i);
            permissionTreeData.setNodeType(PermissionTreeData.ITEM);
            if (roleModulePermissionDao.checkPermission(functionItem.getId(),
                    roleId)) {
                permissionTreeData.setIntChecked(true);
                permissionTreeData.setChecked(true);
            }
            queryItemForConfig(permissionTreeData, roleId);
            permissionTreeDataList.add(permissionTreeData);
        }
        parent.addChild(permissionTreeDataList);
    }

    /**
     * 权限数据保存
     * 
     * @param roleForm
     */
    public void saveForConfigPermission(RoleForm roleForm) {
        if (roleForm.getSystemRole() == null) {
            return;
        }
        String roleId = roleForm.getSystemRole().getId();

        roleModulePermissionDao.delete(roleModulePermissionDao
                .findByRole(roleId));

        String data = roleForm.getPostData();
        if (StringUtil.isNullOrEmpty(data)) {
            return;
        }

        Map<String, String> map = new HashMap<String, String>();
        Gson gson = new Gson();
        PermissionTreeData[] permissionTreeDatas = gson.fromJson(data,
                PermissionTreeData[].class);
        if (permissionTreeDatas != null && permissionTreeDatas.length > 0) {
            for (int i = 0; i < permissionTreeDatas.length; i++) {
                PermissionTreeData permissionTreeData = permissionTreeDatas[i];
                String id = roleModulePermissionDao.addRolePermission(roleId,
                        permissionTreeData.getId());
                if (!map.containsKey(permissionTreeData.getId())) {
                    map.put(permissionTreeData.getId(), id);
                }
            }
        }
    }
}
